"use strict";

const path = require("path");
const fs = require("fs");
const url = require("url");

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;

function ensureSlash(inputPath, needsSlash) {
	const hasSlash = inputPath.endsWith("/");
	if (hasSlash && !needsSlash) {
		return inputPath.substr(0, inputPath.length - 1);
	} else if (!hasSlash && needsSlash) {
		return `${inputPath}/`;
	} else {
		return inputPath;
	}
}

const buildPath = process.env.BUILD_PATH || "build";

const getPublicUrl = appPackageJson => envPublicUrl || require(appPackageJson).homepage;

function getServedPath(appPackageJson) {
	const publicUrl = getPublicUrl(appPackageJson);
	const servedUrl = envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : "/");
	return ensureSlash(servedUrl, true);
}

const moduleFileExtensions = ["web.mjs", "mjs", "web.js", "js", "web.ts", "ts", "web.tsx", "tsx", "json", "web.jsx", "jsx"];

// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
	const extension = moduleFileExtensions.find(extension => fs.existsSync(resolveFn(`${filePath}.${extension}`)));

	if (extension) {
		return resolveFn(`${filePath}.${extension}`);
	}

	return resolveFn(`${filePath}.js`);
};

// config after eject: we're in ./config/
module.exports = {
	appPath: resolveApp("."),
	appBuild: resolveApp(buildPath),
	ssrPath: resolveApp("server"),
	appPublic: resolveApp("public"),
	appHtml: resolveApp("public/index.html"),
	appPackageJson: resolveApp("package.json"),
	appSrc: resolveApp("src"),
	appTsConfig: resolveApp("tsconfig.json"),
	appJsConfig: resolveApp("jsconfig.json"),
	yarnLockFile: resolveApp("yarn.lock"),
	proxySetup: resolveApp("src/setupProxy.js"),
	appNodeModules: resolveApp("node_modules"),
	// appWebpackCache: resolveApp("node_modules/.cache"),
	// appTsBuildInfoFile: resolveApp("node_modules/.cache/tsconfig.tsbuildinfo"),
	// swSrc: resolveModule(resolveApp, "src/service-worker"),
	publicUrl: getPublicUrl(resolveApp("package.json")),
	servedPath: getServedPath(resolveApp("package.json")),
};

module.exports.moduleFileExtensions = moduleFileExtensions;
